(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = global || self, factory(global['yly-form-template'] = {}));
}(this, (function (exports) { 'use strict';

  var FormConfigTemplate = `
  var formConfig = {
    formPageConfig: <%- formPageConfig %>,
    formList: <%- formRenderConfig %>,
    formRequestOptions: {
      formCode: '<%=generateFormParams.formCode || generateFormParams.pageCode%>',
      saveUrl: '<%=generateFormParams.saveUrl%>',
      editUrl: '<%=generateFormParams.editUrl%>',
      queryUrl: '<%=generateFormParams.queryByIdUrl || generateFormParams.queryUrl%>'
    },
  }
  export default formConfig
`;

  var FormRenderTemplate = `
<template>
  <div class="form-code">
    <k-form-build
      ref="editFormComponent"
      :formCode="formRequestOptions.formCode"
      :value="formConfig"
    ></k-form-build>
    <div v-if="isMenuForm" style="text-align: right; margin-right: 16px;">
      <a-button type="primary" @click="saveFormPageData"> {{$t('保存')}} </a-button>
      <a-button @click="clearFormData"> {{$t('清空')}} </a-button>
    </div>
  </div>
</template>
<script>
import KFormBuild from "@/pages/design/module/kFormBuild/index.vue"
import componentsConfig from './components-config'
import cloneDeep from "lodash/cloneDeep"
import CommonEditFormMixin from '@/mixins/CommonEditFormMixin'
export default {
  name: '<%=generateFormParams.formCode%>',
  mixins: [CommonEditFormMixin],
	components: {
    KFormBuild,
  },
	props: {
    isMenuForm: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      componentsConfig: cloneDeep(componentsConfig),
      formRequestOptions: cloneDeep(componentsConfig.formRequestOptions),
      formList: cloneDeep(componentsConfig.formList)
    };
  },
	created() {
    this.initFormPageConfig(this.componentsConfig)
	},
	methods: {
  }
}
</script>
<style lang="scss">
.form-code {
  width: 100%;
}
</style>
`;

  var TableConfigTemplate = ` var TableComponentsConfig = {
  gridOptions: {
    autoResize: true,
    border: true,
    columnConfig: {
      resizable: false
    },
    customLeftButtons: <%- JSON.stringify(customLeftButtons) %>,
    optionsRowButtons: <%- JSON.stringify(optionsRowButtons) %>,
    columns: <%- JSON.stringify(gridOptionsColumns) %>,
    isSearch: <%= tableComponent.isSearch || 0 %>, //是否初始化查询 0 否 1 是
    isPage: <%= tableComponent.isPage || 0 %>, //是否分页 0 否 1 是
    pageConfig: {
      hiddenPageSize: false,
      hideOnSinglePage: false,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '30', '40' ]
    },
    pagination: {
      pageNo: 1,
      pageSize: <%= tableComponent.pageSize || 10 %>,
      total: 0
    }
  },
  formQueryConfig: <%- JSON.stringify(formQueryConfig) %>,
  queryParams: {
    url: '',
    params: {}
  },
  sortType: '<%= sortType || ''%>',
  sortColumn: '<%= sortColumn || ''%>'
}
// columns 列配置说明
// 默认属性不生成， 可自行配置
// title:  展示table 和查询条件名称
// visible: true || false 是否展示
// field: '', table 和查询字段名key,
// sortable: true || false, 是否排序
// formatter: '' 展示形式
// align: 'left' || 'center' || 'right', 对其方式 左 中 呦
// minWidth: 100 最小宽度
// width: '' 宽度
// showOverflow: true || false , 超出宽度省略
export default TableComponentsConfig
`;

  var TableRenderTemplate = `

<template>
  <a-card class="query-card fragement-page" ref="pageCard">
    <test-query-panel
      :formQueryConfig="formQueryConfig"
      :queryParam="queryParam"
      :dictOptions="dictOptions"
      @searchByQuery="searchQuery(true)"
      @searchReset="searchReset"
    ></test-query-panel>
    <g-vxe-grid
      v-bind="gridOptions"
      :height="null"
      @size-change="pageSizeChange"
      @current-page-change="pageNoChange"
      @refreshData="searchQuery(true)"
      ref="xGrid"
    >
      <template v-if="gridOptions.customLeftButtons.length === 0" #toolBarBtn>
        <prefix-title style="margin-left: 8px;"/> 
      </template>
      <template #operation="{ row }">
        <table-options-col
          :optionsRowButtons="optionsRowButtons"
          :rowData="row"
          @rowButtonClick="rowButtonClick"
        ></table-options-col>
      </template>
    </g-vxe-grid>
    <form-edit-modal ref="FormEditModalRef" @updateTableList="searchQuery"/>
    <form-read-modal ref="FormReadModalRef"/>
  </a-card>
  </template>
  <script>
  import { VxeGridMixin } from "@/mixins/VxeGridMixin";
  import TableOptionsCol from '@/components/compose-table-component/table-options-col.vue';
  import FormEditModal from "@/components/compose-table-component/form-edit-modal.vue";
  import FormReadModal from "@/components/compose-table-component/form-read-modal.vue";
  import { queryPrintDefaultTemplate } from "@/api/print";
  import { jsonToPrintTemplate } from '@/pages/print/utils/print.util';
  import TestQueryPanel from "@/pages/design/onlineTest/online-component/test-query-panel.vue";
  import componentsConfig from './components-config'
  import { postAction, getAction } from '@/api/manage'
  import cloneDeep from "lodash/cloneDeep"
  export default {
  name: 'TableTest',
  mixins: [VxeGridMixin],
  components: {
    TableOptionsCol,
    TestQueryPanel,
    FormEditModal,
    FormReadModal
  },
  props: {
  },
  data() {
    return {
      tableRequestOptions: {
        queryUrl: "<%=generateFormParams.queryUrl%>",
        exportUrl: "<%=generateFormParams.exportUrl%>",
        deleteUrl: "<%=generateFormParams.deleteUrl%>",
      },
      componentId: '',
      toggleSearchStatus: false,
      queryParam: {},
      selectedRowKeys: [], // 选中行
      selectionRows: [], //选中列
      componentsConfig: cloneDeep(componentsConfig),
      gridOptions: {
        columns: [],
        columnConfig: {
          resizable : false
        },
        pageConfig: {
          hiddenPageSize: false,
          showSizeChanger: true, // 分页器
          pageSizeOptions: ["15", "30", "45"],
          hideOnSinglePage: false, // 如果数据单页  则隐藏分页功能
        },
        pagination: {
          pageNo: 1,
          pageSize: 15,
          total: 0,
        },
        customLeftButtons: []
      },
      optionsRowButtons: [],
      hasSearch: false,
      isQueryFields: [],
      dictOptions: {}
    };
  },
  computed: {
  },
  created() {
    this.initTableRenderConfig();
  },
  methods: {
    initTableRenderConfig() {
      if(this.componentsConfig) {
        var { gridOptions, formQueryConfig, componentId } = this.componentsConfig
        this.componentId = componentId
        Object.assign(this.gridOptions, gridOptions)
        this.gridOptions.columns.sort((a, b) => a.orderNum - b.orderNum)
        this.gridOptions.columns = this.getDefaultTableColsConfig(this.gridOptions.columns)
        this.initTableQueryControl(formQueryConfig)
        this.initTableButtonConfig(gridOptions)
        this.initPagination()
        if(this.gridOptions.isSearch === 1) {
          this.searchQuery()
        }
      }
    },
    initPagination() {
      if(!parseInt(this.gridOptions.isPage) == 1) {
        this.gridOptions.pagination.pageSize = 9999
        this.gridOptions.pageConfig.hideOnSinglePage = true
      }
    },
    initTableButtonConfig(gridOptions = {}) {
      var {customLeftButtons = [], optionsRowButtons = []} = gridOptions
      customLeftButtons
      .sort((a, b) => a.orderNum - b.orderNum)
      .forEach(item => {
        item.buttonEvent = () => this.tableToolbarClick(item)
      })

      this.optionsRowButtons = optionsRowButtons.sort((a, b) => a.orderNum - b.orderNum)
    },
    initTableQueryControl(formQueryConfig) {
      // 初始化查询条件
      if(Array.isArray(formQueryConfig)) {
        this.formQueryConfig = formQueryConfig
      }
    },
    searchQuery(isInit) {
      if (isInit) {
        Object.assign(this.gridOptions.pagination, componentsConfig.gridOptions.pagination)
      }
      var params = {
        ...this.queryParam,
        pageNo: this.gridOptions.pagination.pageNo,
        pageSize: this.gridOptions.pagination.pageSize,
        sortColumn: this.componentsConfig.sortColumn,
        sortType: this.componentsConfig.sortType
      }
      if(!params.sortColumn) delete params.sortColumn
      if(!params.sortType) delete params.sortType
      var searchUrl = this.tableRequestOptions.queryUrl + '/?pageNo=' + this.gridOptions.pagination.pageNo + '&pageSize=' + this.gridOptions.pagination.pageSize
      postAction(searchUrl, params, '/').then(res => {
        this.gridOptions.data = res.result.records;
        this.gridOptions.pagination.total = res.result.total;
      })
    },
    searchReset() {
      this.queryParam = {};
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    pageSizeChange(pageNo, pageSize) {
      this.gridOptions.pagination.pageNo = pageNo;
      this.gridOptions.pagination.pageSize = pageSize;
      this.searchQuery();
    },
    pageNoChange(pageNo) {
      console.log(pageNo);
      this.gridOptions.pagination.pageNo = pageNo;
      this.searchQuery();
    },
    tableToolbarClick(buttonConfig) {
      if(buttonConfig.dataOpType === 'custom') {
        let componentName = buttonConfig.buttonRefFunctionMethod
        if(componentName){
          let fnModules = componentName.split('.')
          this.$lib[fnModules[0]][fnModules[1]].call(this, {} , this.$refs.xGrid.getSelectedDta() , this)
        }
        return 
      }
      console.log(buttonConfig)
      if(buttonConfig.dataOpType === 'update') {
        this.$message.warning(this.$t('工具栏按钮无法编辑表单'))
      }
      if(buttonConfig.dataOpType === 'insert') {
        if(buttonConfig.openWay === 'new_page') {
          let pathParams = {
            formCode : buttonConfig.buttonRefFormCode
          }
          this.$router.push({
            path: '/form-page/form-new-tab/edit-form',
            query: {
              ...pathParams
            }
          })
        } else {
          try {
            var formConfig = require('@/pages/form-page/form-component/' + buttonConfig.buttonRefFormCode + '/components-config.js').default
            if(!formConfig || !Array.isArray(formConfig.formList)) {
              throw new Error('获取表单配置异常')
            }
            this.$refs.FormEditModalRef.openModal({
              formConfig, buttonConfig
            })
          } catch(err) {
            this.$message.warning(this.$t('加载表单配置异常') + ',' + this.$t('请确认表单类型是否正确') + '!')
            console.log(err)
          }
        }
      } else if(buttonConfig.dataOpType === 'print') {
        this.handleToPrint()
      } else if(buttonConfig.dataOpType === 'export') {
        this.handleExportTableComponentData()
      }
    },
    rowButtonClick(buttonConfig, rowData) {
      if(buttonConfig.dataOpType === 'custom') {
        let componentName = buttonConfig.buttonRefFunctionMethod
        if(componentName){
          let fnModules = componentName.split('.')
          this.$lib[fnModules[0]][fnModules[1]].call(this, {} , rowData , this.$refs.pageCard )
        }
        return 
      }
      if(buttonConfig.dataOpType === 'delete') {
        this.handleDeleteTableData(rowData)
      }
      let pathParams = {
        formCode : buttonConfig.buttonRefFormCode,
        rowId: rowData.id
      }
      if(['insert', 'update'].includes(buttonConfig.dataOpType)) {
        try {
          var formConfig = require('@/pages/form-page/form-component/' + buttonConfig.buttonRefFormCode + '/components-config.js').default
          if(!formConfig || !Array.isArray(formConfig.formList)) {
            throw new Error('获取表单配置异常')
          }
          this.$refs.FormEditModalRef.openModal({
            formConfig, buttonConfig, rowData
          })
        } catch(err) {
          this.$message.warning(this.$t('加载表单配置异常') + ',' + this.$t('请确认表单类型是否正确') + '!')
          console.log(err)
        }
      } else if(['detail'].includes(buttonConfig.dataOpType)) {
        if(buttonConfig.openWay === 'new_page') {
          this.$router.push({
            path: '/form-page/form-new-tab/show-form',
            query: {
              ...pathParams
            }
          })
        } else {
          try {
            var formConfig = require('@/pages/form-page/show-component/' + buttonConfig.buttonRefFormCode + '/components-config.js').default
            if(!formConfig || !Array.isArray(formConfig.formList)) {
              throw new Error('获取表单配置异常')
            }
            this.$refs.FormReadModalRef.openModal({
              formConfig, buttonConfig, rowData
            })
          } catch(err) {
            this.$message.warning(this.$t('加载表单配置异常') + ',' + this.$t('请确认表单类型是否正确') + '!')
            console.log(err)
          }
        }
      } else if(buttonConfig.dataOpType === 'print') {
        this.handleToPrint(rowData)
      } else if(buttonConfig.dataOpType === 'export') {
        this.handleExportTableComponentData()
      }
    },
    handleDeleteTableData(rowData) {
      this.$confirm({
        title: this.$t('确定') + '?',
        content: this.$t('是否删除'),
        okText: this.$t('确定'),
        cancelText: this.$t('取消'),
        onOk: () => {
          var urlParams = {
            id: rowData.id
          }
          var bodyParams = {}
          getAction(this.tableRequestOptions.deleteUrl, urlParams, '/').then(res => {
            if(res.code === 200) {
              this.$message.success(this.$t('删除成功'))
              this.searchQuery()
            }
          })
        }
      })
    },
    handleToPrint(rowData) {
      let allRowData = []
      if(!rowData) {
        allRowData = this.$refs.xGrid.getSelectedDta();
      } else {
        allRowData = [rowData]
      }
      if (allRowData.length === 0) return this.$message.warning(this.$t('请选中要打印的数据'))
      queryPrintDefaultTemplate({}, this.$route.query.projectCode).then(res => {
        if (res.result.templateText) {
          var printTemplate = jsonToPrintTemplate(res.result.templateText)
          if (!printTemplate) {
            return console.warn('解析打印模板失败')
          }
          if (window.hiwebSocket.opened) {
            // var printerList = printTemplate.getPrinterList()
            allRowData.forEach(rowData => {
              var printData = { ...rowData }
              var needShowTextFields = Object.keys(rowData).filter(field => field.substring(field.length - 7, field.length) === 'ShowTxt')
              if (needShowTextFields && needShowTextFields.length > 0) {
                needShowTextFields.forEach(field => {
                  if (field.substring(0, field.length - 7)) {
                    printData[field.substring(0, field.length - 7)] = rowData[field] || printData[field.substring(0, field.length - 7)]
                  }
                })
              }
              printTemplate.print2(printData, { paperNumberToggleInEven: true })
            })
            return
          }
          this.$message.error(this.$t('客户端未连接,无法直接打印'))
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleExportTableComponentData() {
      var { pageNo, pageSize } = this.gridOptions.pagination
      var params = {
        tableId: this.componentId,
        pageNo,
        pageSize,
        sortType: 'asc'
      }
      postAction(this.tableRequestOptions.exportUrl, params, '/').then(res => {
        console.log(res)
        this.$confirm({
          title: this.$t('导出成功'),
          content: this.$t('是否跳转到下载中心下载文件') + '?',
          okText: this.$t('确定'),
          cancelText: this.$t('取消'),
          onOk: () => {
            var pathParams = {
              projectId : this.$route.query.projectId,
              projectCode: this.$route.query.projectCode
            }
            this.$router.push({
            path: '/download-center',
              query: {
                ...pathParams
              }
            })
          }
        })
      })
    }
  },
  };
  </script>
  <style scoped>
  @import "~assets/less/common.less";
  .ant-calendar-picker {
  min-width: 0px !important;
  }
  </style>
  <style lang="scss">
  .fragement-page {
  height: 100%;
  padding: 12px;
  .query-table {
    flex: auto !important;
  }
  }
  </style>
`;

  var ShowRenderTemplate = `
<template>
  <div class="form-code">
    <k-form-build
      ref="formCode"
      :renderScene="'read'"
      :value="formConfig"
      :formCode="formRequestOptions.formCode"
    ></k-form-build>
  </div>
</template>
<script>
import KFormBuild from "@/pages/design/module/kFormBuild/index.vue"
import componentsConfig from './components-config'
import cloneDeep from "lodash/cloneDeep"
export default {
  name: '<%=generateFormParams.pageCode%>',
	components: {
    KFormBuild,
  },
	props: {
  },
  data() {
    return {
      formRequestOptions: cloneDeep(componentsConfig.formRequestOptions),
      formList: cloneDeep(componentsConfig.formList)
    };
  },
	created() {
    this.initFormConfig()
	},
	methods: {
    initFormConfig() {
      this.formConfig = {
        config: {},
        list: this.formList
      }
    }
  }
}
</script>
<style lang="scss">
.form-code {
  width: 100%;
}
</style>
`;

  var PageRenderTemplate = `
<template>
	<div class="compose-page">
		<a-card class="app-card" style="width: 100%; height: 100%;" ref="pageCard">
		<%_ componentListConfig.forEach(function(item){ _%>
			<div
				class="compose-page-menu <%= item.componentType === 'table' ? 'compose-table-menu' : 'compose-form-menu'%>"
				style="margin-top: 5px; border: 1px dashed #e5e5e5"
			>
				<div class="form-item-box">
					<%_ if(item.componentType === 'baseButton') { _%>
						<a-button type='<%=item.type%>' @click="event => elementOnClick(event , '<%=item.onClick.eventModule%>' , '<%=item.onClick.eventFunctionName%>')">
							{{ '<%=item.label%>' }}
						</a-button>
					<%_ } else if(item.componentType === 'baseButtonGroup') { _%>	
						<div style="text-align:<%=item.textAlign%>;">
						<%_ item.btnList.forEach(function(btn){ _%>
							<a-button type='<%=btn.type%>' @click="event => elementOnClick(event , '<%=btn.onClick.eventModule%>' , '<%=btn.onClick.eventFunctionName%>')">
								{{ '<%=btn.label%>' }}
							</a-button>
						<%_ }) _%>	
						</div>
					<%_ } else { _%>	
						<<%=item.componentCode%>
							ref="<%=item.componentCode%>"
							<%_ if(item.componentType === 'form') { _%>
							:isMenuForm="<%= !needCustomCodePageConfig.ShowPageSaveBtn %>"
							<%_ } _%>	
						/>
					<%_ } _%>	
				</div>
			</div>
		<%_ }) _%>	
		</a-card>
	</div>
</template>
<script>
<%_ componentListConfig.forEach(function(item){ _%>
<%_ if(item.componentType === 'baseButton' || item.componentType === 'baseButtonGroup') { _%>
<%_ } else { _%>	
import <%=item.componentCode%> from "@/pages/form-page/<%= item.componentTypePath %>/<%=item.componentCode%>/index.vue"
<%_ } _%>	
<%_ }) _%>	

import CloudPageBtnMixin from '@/mixins/CloudPageBtnMixin.js'
export default {
	name: '<%=needCustomCodePageConfig.pageCode%>Page',
	components: {
		<%_ componentListConfig.forEach(function(item){ _%>
			<%_ if(item.componentType !== 'baseButton' && item.componentType !== 'baseButtonGroup') { _%>
				<%= item.componentCode %> : <%= item.componentCode %>,
			<%_ } _%>
		<%_ }) _%>	
	},
	mixins: [ CloudPageBtnMixin ],
	data(){
		return {
		}
	},
	created() {},
	methods: {
	}	
}

</script>

`;

  var MobileFormRenderTemplate = `
<template>
	<div>
		<mobile-form-render
			class="mobile-preview"
			:value="formData"
			:formCode="formRequestOptions.formCode"
			:formRequestOptions="formRequestOptions"
		/>
	</div>
</template>

<script>
import MobileFormRender from "@/components/mobile-form-render";
import formConfig from './components-config'
import cloneDeep from "lodash/cloneDeep"
export default {
	name: '<%=generateFormParams.formCode%>',
	components: {
		MobileFormRender,
	},
	data() {
		return {
			formData: {
				list: [],
				config: formConfig.formPageConfig,
				fields: []
			},
			formRequestOptions: {}
		};
	},

	created() {
		this.formData.list = cloneDeep(formConfig.formList)
		this.formRequestOptions = cloneDeep(formConfig.formRequestOptions)
	},

	methods: {},
};
</script>
`;

  var MobilePageRenderTemplate = `
<template>
	<div class="compose-page">
		<%_ componentListConfig.forEach(function(item){ _%>
			<div class="form-item-box">
				<%_ if(item.componentType === 'baseButton') { _%>
					<a-button type='<%=item.type%>' @click="event => elementOnClick(event , '<%=item.onClick.eventModule%>' , '<%=item.onClick.eventFunctionName%>')">
						{{ '<%=item.label%>' }}
					</a-button>
				<%_ } else if(item.componentType === 'baseButtonGroup') { _%>	
					<div style="text-align:<%=item.textAlign%>;">
					<%_ item.btnList.forEach(function(btn){ _%>
						<a-button type='<%=btn.type%>' @click="event => elementOnClick(event , '<%=btn.onClick.eventModule%>' , '<%=btn.onClick.eventFunctionName%>')">
							{{ '<%=btn.label%>' }}
						</a-button>
					<%_ }) _%>	
					</div>
				<%_ } else { _%>	
					<<%=item.componentCode%>
						ref="<%=item.componentCode%>"
						<%_ if(item.componentType === 'form') { _%>
						:isMenuForm="<%= !needCustomCodePageConfig.ShowPageSaveBtn %>"
						<%_ } _%>	
					/>
				<%_ } _%>	
			</div>
		<%_ }) _%>	
	</div>
</template>
<script>
<%_ componentListConfig.forEach(function(item){ _%>
<%_ if(item.componentType === 'baseButton' || item.componentType === 'baseButtonGroup') { _%>
<%_ } else { _%>	
import <%=item.componentCode%> from "@/pages/form-page/<%= item.componentTypePath %>/<%=item.componentCode%>/index.vue"
<%_ } _%>	
<%_ }) _%>	
export default {
	name: '<%=needCustomCodePageConfig.pageCode%>Page',
	components: {
		<%_ componentListConfig.forEach(function(item){ _%>
			<%_ if(item.componentType !== 'baseButton' && item.componentType !== 'baseButtonGroup') { _%>
				<%= item.componentCode %> : <%= item.componentCode %>,
			<%_ } _%>
		<%_ }) _%>	
	},
	data(){
		return {
		}
	},
	created() {},
	methods: {
	}	
}

</script>

`;

  exports.FormConfigTemplate = FormConfigTemplate;
  exports.FormRenderTemplate = FormRenderTemplate;
  exports.MobileFormRenderTemplate = MobileFormRenderTemplate;
  exports.MobilePageRenderTemplate = MobilePageRenderTemplate;
  exports.PageRenderTemplate = PageRenderTemplate;
  exports.ShowRenderTemplate = ShowRenderTemplate;
  exports.TableConfigTemplate = TableConfigTemplate;
  exports.TableRenderTemplate = TableRenderTemplate;

  Object.defineProperty(exports, '__esModule', { value: true });

})));
